package com.example.demo.controller;

import com.example.demo.entity.Medical;
import com.example.demo.entity.Response;
import com.example.demo.service.Impl.MedicalImpl;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.lang.String;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static java.time.LocalDateTime.now;
import static java.util.Map.of;
import static org.springframework.http.HttpStatus.CREATED;

@RestController
@RequestMapping("/medical")
@RequiredArgsConstructor

public class MedicalController {
    private final MedicalImpl medicalImpl;
//    @Value("${hong.path}")
    private final String basePath = "D:/aaa/";
    @PostMapping("/upload")
    public ResponseEntity<Response> upload(@RequestParam("files") List<MultipartFile> files,
                                           @RequestParam("applicationId") Long applicationId) {
        System.out.println("Received files: " + files.size());
        System.out.println("Received applicationId: " + applicationId);
        return ResponseEntity.ok(
                Response.builder()
                        .timeStamp(now())
                        .data(of("uploadFile",medicalImpl.uploadToLocal(files,applicationId,basePath)))
                        .message("上传附件")
                        .status(CREATED)
                        .statusCode(CREATED.value())
                        .build()
        );
    }
    @GetMapping("/getDownloadUrl/{applicationId}")
    public ResponseEntity<Response> getDownloadUrl(@PathVariable Long applicationId){
        return ResponseEntity.ok(
                Response.builder()
                        .timeStamp(now())
                        .data(of("file",medicalImpl.getDownloadUrl(applicationId)))
                        .message("下载附件")
                        .status(CREATED)
                        .statusCode(CREATED.value())
                        .build()
        );
    }
    @GetMapping("/downloadOneFile/{medicalId}")
    public ResponseEntity<Resource> downloadOneFile(@PathVariable Long medicalId) throws IOException {
        Medical medical = medicalImpl.findById(medicalId);
        System.out.println(medical.getMedicalName());
        if (medical == null) return ResponseEntity.notFound().build();
        String filePath = medical.getMedicalUrl();
        // 从文件路径中获取文件资源
        FileSystemResource resource = new FileSystemResource(filePath);
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }
        // 获取文件名
        String filename = resource.getFilename();
//        if (filename == null || filename.isEmpty()) {
//            return ResponseEntity.badRequest().build();
//        }
        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"");
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }

    @GetMapping("/getUrl/{applicationId}")
    public ResponseEntity<Resource> downloadFile(@PathVariable Long applicationId) {
        try {
            String filePath = medicalImpl.getFilePathByApplicationId(applicationId); // 获取文件路径的方法
            Resource file = new FileSystemResource(filePath);

            if (!file.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"");
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(file.contentLength())
                    .body(file);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
}
